var config = require('../../config.js')
var CryptoJS = require('./../../util/util.js');

const app = getApp()
Page({
  /**
   * 页面的初始数据
   */
  data: {
    msg_null_dtg:false,
    uuid:"",
    phone: "",
    host_user:0,
    page:0,
    pagesize:10,
    msg_list: [],
    curtimestamp:0,
    showMsgpopup: false,
    dialogShowDg: false,
    unlockValue: "",
    unlocktimestamp:0,
    timevalue: 0,
    msg_pic_url:'',
    msg_alarm_time:'',
    msg_title_txt:'输入开锁密码',

    setInter: 0,
    confirm_btn_txt:'确认开锁',
    unlocktime:'',
    confirm_btn: false
  },

  mqttPublish(key, data) {
    let _this = this
    return //test
    try{
      if (!app.globalData.MQ || !app.globalData.MQ.connected) {
      //  app.AppGetDevList()
        app.initSocket()
        setTimeout(function () {
        //  console.log("mqttPublish 11111", app.globalData.MQ.connected);
          if (app.globalData.MQ.connected)
          {
            app.globalData.MQ.publish(config.mqtt_baidu.unlock_top, data);
          }
          
        }, 1000)
        return
      }
    // console.log("mqttPublish 2222222");
      app.globalData.MQ.publish(config.mqtt_baidu.unlock_top, data);
      // setTimeout(function () {
      //   app.globalData.MQ.publish(key, data);
      // }, 100)
    }
          catch(err) {
      console.log('publish fail', err)
      return
    }
  },

  to_onUnlockClick(e) {
    var _this = this
  //  console.log('to_onUnlockClick',e, this.data.unlockShowDg)
    // console.log('to_onUnlockClick', e.currentTarget.dataset.value.fields.timestamp, this.data.unlockShowDg)

    {
      var msg_type = e.currentTarget.dataset.value.fields.msg_type
      var hTime = e.currentTarget.dataset.value.fields.timestamp
      var qTime = parseInt(new Date().getTime() / 1000)

      //  console.log('hTime', hTime, 'qTime', qTime)
       console.log('msg_type', msg_type,  '时间', qTime - hTime)
      if ((hTime > 1) && (e.currentTarget.dataset.index == 0)) {
        if ((msg_type == 3) || (msg_type == '3')) {

          if (qTime - hTime < 60) {//60
            var unlockt = hTime + 65 - qTime;

            _this.data.setInter = setInterval(function () {
              // console.log('unlockt', unlockt)
              if (unlockt > 1) {
                unlockt--;

                _this.setData({
                  unlocktime: unlockt
                })
              }
              else {
                clearInterval(_this.data.setInter)
                _this.setData({
                  unlockShowDg: false,
                  confirm_btn: false,
                })
              }

            }, 1000) //延迟时间 这里是1秒

            this.setData({
              dialogShowDg: true,
              confirm_btn: true,
              unlocktime: unlockt,
              unlockShowDg: true

            })

          }

        }
      }
      else {
        clearInterval(_this.data.setInter)
        _this.setData({
          unlockShowDg: false,
          confirm_btn: false,
        })
      }

    }



    // if(unlock > 0)
    // {
    //   this.setData({
    //     dialogShowDg: true,
    //     unlockShowDg: true,
    //     confirm_btn: true,
    //     // unlocktime: unlockt,
    //     unlocktimestamp: e.currentTarget.dataset.value.fields.timestamp
    //   })
    // }
   
    
  },

  sendUnlock(uuid, phone, lockpwd, unlocktimestamp, timevalue)
  {
    // console.log('uuid',uuid,"phone",phone)
    // console.log('lockpwd', lockpwd, "unlocktimestamp", unlocktimestamp, "timevalue", timevalue)
    var _this = this
    this.setData({
      dialogShowDg: false
    })

    var pwd = CryptoJS.Encrypt(lockpwd)
    wx.request({
      url: config.url.checkUnlockPwd,
      method: 'POST',
      dataType: "json",
      data: {
        uuid: uuid,
        phone: phone,
        password: pwd,
        timestamp: unlocktimestamp,
        value: timevalue,
        client: config.client,
      },
      header: {
        // 'content-type': 'application/json', // 默认值
        "Content-Type": "application/x-www-form-urlencoded;charset=utf-8"
      },
      success(res) {
        console.log(res.data)
        console.log("code:", res.data.code)
        console.log("data:", res.data.data)

        if (res.data.code == 200) {
          // var timestamp = new Date().getTime();
          var msg = { "code": "200", "uuid": uuid, "token": res.data.data, "timestamp": unlocktimestamp + "", "phone": phone}
          _this.mqttPublish(uuid, JSON.stringify(msg))
        }
        else {
          wx.showToast({
            title: '请输入正确的开锁密码',
            icon: 'none',
            duration: 2000
          })

        }

      },
      fail(e) {
        console.error(e)
     
      }
    })
  },

  onUnlockChange(e) {
    // console.log(e)
    var _this = this
    // console.log("onUnlockChange:", e.detail,"length:",e.detail.length)
    this.setData({
      unlockValue: e.detail
    })
    // console.log("unlockValue:", this.data.unlockValue)

    if(e.detail.length == 6)
    {
      var timestamp = parseInt(new Date().getTime() / 1000)
      _this.sendUnlock(_this.data.uuid, _this.data.phone, e.detail, timestamp, _this.data.timevalue)
    
      _this.setData({
        unlockShowDg: false,
        confirm_btn: false,
      })
      clearInterval(_this.data.setInter)
    
      // if (_this.data.unlocktimestamp == 0)
      // {
      //   //app.globalData.timevalue
      //   _this.sendUnlock(_this.data.uuid, _this.data.phone, e.detail, app.globalData.timestamp, _this.data.timevalue)
      // }
      // else
      // {
      //   //app.globalData.timevalue
      //   _this.sendUnlock(_this.data.uuid, _this.data.phone, e.detail, _this.data.unlocktimestamp, _this.data.timevalue)
      // }
     
    }
   
  },

  onUnlockConfirm(e) {
    var _this = this
    console.log("uuid", this.data.uuid)
    console.log("onUnlockConfirm", this.data.unlockValue)
    // var pwd = CryptoJS.Encrypt(this.data.unlockValue)
    // this.mqttPublish(this.data.uuid,"123456789")

    if (_this.data.phone == "") 
    {
      var phone = wx.getStorageSync('phone')
      console.log("cz phone:", phone)
      if (phone != "") 
      {
        _this.setData({
          phone: phone
        })
      }
    }
    if(_this.data.unlockValue == 6)
    {
      var timestamp = parseInt(new Date().getTime() / 1000)
      _this.sendUnlock(_this.data.uuid, _this.data.phone, _this.data.unlockValue, timestamp, _this.data.timevalue)

      // _this.sendUnlock(_this.data.uuid, _this.data.phone, _this.data.unlockValue, _this.data.unlocktimestamp, _this.data.timevalue)
    }
    else
    {
        wx.showToast({
        title: '请输入正确的开锁密码',
        icon: 'none',
        duration: 2000
      })
    }
   
   
  },

  onClose() {
    clearInterval(this.data.setInter)
    this.setData({
      dialogShowDg: false
    })
  },
  // msg_list: ['1', '2', '3', '1', '2', '3']
  //dev_uuid: 11, msg_type: "远程开锁请求", pic_url: "20200429120816.jpg", msg_time: "2021-03-28 20:08:15", time: "2020-04-29",
  to_onSetting(e){
    var _this = this
    console.log("to_onSetting:", e)
    wx.navigateTo({
      url: '../equipment_set/equipment_set?uuid=' + _this.data.uuid + "&host_user=" + _this.data.host_user,
    })
  },

  //_this.formatDate(new Date(parseInt(data.timestamp + "000")));
  // formatDate(now) {
  //   var year = now.getFullYear();  //取得4位数的年份
  //   var month = now.getMonth() + 1;  //取得日期中的月份，其中0表示1月，11表示12月
  //   var date = now.getDate();      //返回日期月份中的天数（1到31）
  //   var hour = now.getHours();     //返回日期中的小时数（0到23）
  //   var minute = now.getMinutes(); //返回日期中的分钟数（0到59）
  //   var second = now.getSeconds(); //返回日期中的秒数（0到59）
  //   return year + "-" + this.Appendzero(month) + "-" + this.Appendzero(date) + " " + this.Appendzero(hour) + ":" + this.Appendzero(minute) + ":" + this.Appendzero(second);
  // },
  
  to_onClick(e){
    var _this = this
    console.log("to_onClick:",e)

    this.setData({
      msg_title_txt: e.currentTarget.dataset.value.fields.msg_type_str,
      msg_alarm_time: e.currentTarget.dataset.value.fields.msg_time,
      msg_pic_url: e.currentTarget.dataset.value.fields.pic_url + e.currentTarget.dataset.value.fields.pic_temp_rotate,
    })

    {
      var msg_type = e.currentTarget.dataset.value.fields.msg_type
      var hTime = e.currentTarget.dataset.value.fields.timestamp
      var qTime = parseInt(new Date().getTime() / 1000)

      // console.log('hTime', hTime, 'qTime', qTime)
      // console.log('msg_type', msg_type,  '时间', qTime - hTime)
      if ((hTime > 1) && (e.currentTarget.dataset.index==0))
      {
        if ((msg_type == 3) || (msg_type == '3')) {

          if (qTime - hTime < 60) {//60
            var unlockt = hTime + 65 - qTime;

            _this.data.setInter = setInterval(function () {
              // console.log('unlockt', unlockt)
              if (unlockt > 1) {
                unlockt--;

                _this.setData({
                  unlocktime: unlockt
                })
              }
              else {
                clearInterval(_this.data.setInter)
                _this.setData({
                  unlockShowDg: false,
                  confirm_btn: false,
                })
              }

            }, 1000) //延迟时间 这里是1秒

            this.setData({
              confirm_btn: true,
              unlocktime: unlockt,
              unlockShowDg: true

            })

          }

        } 
      }
      else {
        clearInterval(_this.data.setInter)
        _this.setData({
          unlockShowDg: false,
          confirm_btn: false,
        })
      }
     
    }

    this.setData({
      dialogShowDg: true,
    })
    
    // wx.navigateTo({
    //   url: '../msg_details/msg_details?uuid=' + this.data.uuid + '&data=' + JSON.stringify(e.currentTarget.dataset.value.fields )+ '&index=' + e.currentTarget.dataset.index,
    // })


  },

 
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var _this = this
    // uuid
    console.log(options)
    // console.log('uuid:' + options.uuid)
    // console.log('phone:' + options.phone)
    // console.log('unlock:' + options.unlock)
    var phone = wx.getStorageSync('phone')
    if ((options.phone == '') || (options.phone == 'undefined'))
    {
       phone = wx.getStorageSync('phone')
    }
    else
    {
       phone = options.phone 
    }

    if ((options.unlock != 'undefined') && (options.unlock != undefined))
    {
      console.log("cz alarm_info:", app.globalData.alarm_info)
      console.log("cz imgsrc:", app.globalData.msg_imgurl)
      console.log("cz msg_time:", app.globalData.msg_time)
  
      if (options.unlock == "远程开锁请求" )
      {

        this.setData({
          msg_title_txt: options.unlock,
          msg_alarm_time: app.globalData.msg_time,
          msg_pic_url: app.globalData.msg_imgurl,
        })

        var hTime = parseInt(options.timestamp)
        var qTime = parseInt(new Date().getTime() / 1000)

        console.log('hTime', hTime, 'qTime', qTime)
        console.log('时间', qTime - hTime)
        if (qTime - hTime < 60) {//60
          
          var unlockt = (hTime + 65) - qTime;
          // console.log('hTime', hTime, 'qTime', qTime,  '时间', ((hTime + 65) - qTime))
          // console.log('unlockt0', unlockt)

          _this.data.setInter = setInterval(function () {
             console.log('unlockt', unlockt)
            if (unlockt > 1) {
              unlockt--;

              _this.setData({
                unlocktime: unlockt
              })
            }
            else {
              clearInterval(_this.data.setInter)
              _this.setData({
                unlockShowDg: false,
                confirm_btn: false,
              })
            }

          }, 1000) //延迟时间 这里是1秒

          console.log('unlockt1', unlockt)
          this.setData({
            confirm_btn: true,
            unlocktime: unlockt,
            unlockShowDg: true,
            dialogShowDg: true,
          })

        }


        // this.setData({
        //   dialogShowDg: true,
        //   confirm_btn: true,
        //   unlockShowDg: true
        // })
      }
     
    }
   
    console.log("cz phone:", phone)

  // wx.getStorageSync('phone')
    if ((phone != "") && (phone != "")) {
     // console.log('phone', phone)
      phone = wx.getStorageSync('phone')
    }
    else {
      phone = wx.getStorageSync('phone')
      wx.reLaunch({
        url: '../login/login?id=' + phone,
      })
    }

    this.setData({
      uuid: options.uuid,
      phone: phone,
      host_user: options.host_user,
    })
  },

  getDeviceMsgList: function()
 {
   var __this = this
    wx.showToast({ title: '', icon: 'loading', duration: 10000 });
   wx.request({
     url: config.url.getMsgList,
     method: 'POST',
     data: {
       'phone': this.data.phone,
       'uuid': this.data.uuid,
       'page': this.data.page,
       'client': config.client,
     },
     header: {
       "Content-Type": "application/x-www-form-urlencoded;charset=utf-8"
     },
     success(res) {
      //  console.log("msg_list:", res)
       wx.hideToast();
       if (res.data.code == 0) {

         __this.setData({
           pagesize: res.data.count
           
         })

         let msg_list = res.data.data.map(item => {
           // 显示文字映射需要拼接凭借3个值
           // item.fields.show_text = '门已打开'
           item.fields.show_text = item.fields.msg_type_str
           item.fields.show_user = ""
           // 处理icon图片地址
           if (item.fields.msg_type == 0) {
             item.fields.imgIconSrc = 'close_lock@2x.png'  //ic_lock_open@2x.png'
             if ((item.fields.user_rename != "") && (item.fields.user_rename != "0"))
             {
               item.fields.show_user = "" + config.msg_user[String(item.fields.msg_user)] + ":" + item.fields.user_rename
             }
             else{
               item.fields.show_user = "" + config.msg_user[String(item.fields.msg_user)] + ":" + item.fields.user_id
             }
             
           }
           else if (item.fields.msg_type == 1) {
             item.fields.imgIconSrc = 'ic_lock_open@2x.png'
             if ((item.fields.user_rename != "") && (item.fields.user_rename != "0")) {
               item.fields.show_user = "" + config.msg_user[String(item.fields.msg_user)] + ":" + item.fields.user_rename
             }
             else {
             item.fields.show_user = "" + config.msg_user[String(item.fields.msg_user)] + ":" + item.fields.user_id
             }
           }
           else if (item.fields.msg_type == 2) {
             if (item.fields.msg_value == 2) {
               item.fields.imgIconSrc = 'ic_fingerprint_open.png'
             }
             else if (item.fields.msg_value == 4) {
               item.fields.imgIconSrc = 'ic_card_opendoor.png'
             }
             else
               item.fields.imgIconSrc = 'warring@2x.png'
           }
           else if (item.fields.msg_type == 3)
             item.fields.imgIconSrc = 'netunlock.png'
           else if (item.fields.msg_type_value == 4) {
             if (item.fields.msg_type == 8)
               item.fields.imgIconSrc = 'lowbat@2x.png'
             else if (item.fields.msg_type == 12)
               item.fields.imgIconSrc = 'meng@2x.png'
             else
               item.fields.imgIconSrc = 'yichang@2x.png'
           }
           else
             item.fields.imgIconSrc = 'warring@2x.png'
           // 图片路径拼接处理  
           if (item.fields.pic_url) {
            
             item.fields.pic_temp_rotate = ""
             if (item.fields.value ==2)
             {
               item.fields.pic_temp_rotate = config.pic_rotate + "90"
             }
             else if (item.fields.value == 3) {
               item.fields.pic_temp_rotate = config.pic_rotate + "180"
             }
             
                item.fields.pic_url = config.url.CosImgUrl + item.fields.client + '/' + __this.data.uuid + '/' + item.fields.pic_url 
            //  item.fields.pic_url = 'http://apaicn.com/resources/' + __this.data.uuid + '/' + item.fields.pic_url
           }
           return { ...item }
         })
        //  console.log("length:", msg_list.length, 'msg_list:', msg_list)

         if (__this.data.page == 0)
         {
           __this.setData({
             msg_list: msg_list,
           })
         }
         else
         {
           __this.setData({
             msg_list: __this.data.msg_list.concat(msg_list),
           })
         }
       


         if(msg_list.length > 0)
         {
            __this.setData({
              timevalue: msg_list[0].fields.value
            })
         }

       }


     },
     fail(err) {
       console.err(err)
       wx.hideToast();
     }

   })

   this.setData({
    msg_null_dtg:true
   })
 },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
  

    this.setData({
      curtimestamp: new Date().getTime() / 1000
    })
  },

  onShow() {
    console.log("onShow");
    this.setData({
      showMsgpopup: true,
      curtimestamp: new Date().getTime() / 1000
    })
    // app.AppGetDevList();
    this.getDeviceMsgList()
  },
  onHide() {
    this.setData({
      showMsgpopup: false,
      unlockShowDg: false,
      confirm_btn: false,
    })
    clearInterval(this.data.setInter)
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    console.log('onPullDownRefresh')
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

    if(this.data.pagesize < 10)
    {
      wx.showToast({
        title: '已经到底了',
        icon: 'none',
        duration: 2000
      })
    }
    else
    {
      this.setData({
        page: this.data.page + 1
      })
      this.getDeviceMsgList()
      this.setData({
        curtimestamp: new Date().getTime() / 1000
      })
    }
    // console.log('onReachBottom page:', this.data.page)
    // console.log('onReachBottom pagesize:', this.data.pagesize)
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})